//
//  MTAddFriendViewController.swift
//  MT
//
//  Created by ooops on 2020/2/22.
//  Copyright © 2020 张强. All rights reserved.
//

import UIKit
import GrowingTextView
import MTCategory
import YPNavigationBarTransition
import Result

protocol MTVerficateDetailViewControllerDelegate: NSObjectProtocol {
    /// 拒绝好友请求
    func rejectInvitation()
    /// 同意好友请求
    func confrimInvitation(userName: String)
}

class MTVerficateDetailViewController: BaseViewController {
    
    weak var delegate: MTVerficateDetailViewControllerDelegate?
    
    private lazy var provider: MTProvider<MineApi> = {
        return MTProvider<MineApi>(plugins: [])
    }()
    
    var info: JCVerificationInfo? {
        didSet {
            invitationMessageView.text = info?.resaon ?? ""
            if let uname = info?.username {
                getInfo(username: uname)
            }
        }
    }
    var displayText: String?
    
    private func getInfo(username: String) {
        provider.rx.requestResult(.info(username)).subscribe(onNext: { [weak self] (result: Result<MineInfoResponseModel, AnyError>, isCache: Bool) in
            
            guard let weakSelf = self else {
                return
            }
            switch result {
            case let .success(response):
                
                if let code = response.code, code == 200 {
                    if let result = response.result {
                        weakSelf.model = result
                    }
                } else {
                    if let msg = response.message {
                        AlertManager.presentAlertView(message: msg)
                    }
                }
                break
                
            case let .failure(error):
                AlertManager.presentAlertView(message: error.localizedDescription)
                break
            }
        }).disposed(by: globalDisposedBag)
    }
    
    var model: MineInfoModel? {
        didSet {
            guard let model = model else { return }

            /// 头像
            if let avatar = model.headerUrl {
                avatorImageView.kf.setImage(with: URL(string: avatar), placeholder: UIImage(named: defaultPlaceholderIcon60x60))
            }

            /// 性别
            sexImageView.image = UIImage(named: model.sex == 0 ? "icon_male_small" : "icon_female_small")
            /// 昵称
            nameLabel.text = model.nickname
            /// 用户信息
            if model.age != nil && model.area != nil {
                ageLabel.text = "\(model.age ?? 0)岁 | \(model.area ?? "")"
            } else if model.area == nil {
                ageLabel.text = "\(model.age ?? 0)岁"
            } else {
                ageLabel.text = "\(model.area ?? "")"
            }
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "新的好友"
        setupUI()
        makeConstraint()
        invitationMessageView.isEditable = false
    }
    
    private func setupUI() {
        view.addSubview(avatorImageView)
        view.addSubview(sexImageView)
        view.addSubview(nameLabel)
        view.addSubview(ageLabel)
        
        view.addSubview(invitationMessageView)
        view.addSubview(cofrimBtn)
        view.addSubview(rejectBtn)
    }
    
    private func makeConstraint() {
        
        avatorImageView.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(16)
            make.top.equalToSuperview().offset(26)
            make.width.height.equalTo(80)
        }
        
        sexImageView.snp.makeConstraints { (make) in
            make.right.bottom.equalTo(avatorImageView)
            make.width.height.equalTo(20)
        }
        
        nameLabel.snp.makeConstraints { (make) in
            make.left.equalTo(avatorImageView.snp.right).offset(12)
            make.top.equalTo(avatorImageView).offset(14)
            make.right.equalToSuperview().offset(-80)
        }
        
        ageLabel.snp.makeConstraints { (make) in
            make.left.equalTo(nameLabel)
            make.top.equalTo(nameLabel.snp.bottom).offset(8)
        }
        
        invitationMessageView.snp.makeConstraints { (make) in
            make.top.equalTo(avatorImageView.snp.bottom).offset(40)
            make.left.equalTo(avatorImageView)
            make.right.equalToSuperview().offset(-16)
            make.height.equalTo(106)
            make.centerX.equalToSuperview()
        }
        
        cofrimBtn.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.top.equalTo(invitationMessageView.snp.bottom).offset(110)
            make.width.equalTo(210)
            make.height.equalTo(44)
        }
        
        rejectBtn.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.top.equalTo(cofrimBtn.snp.bottom).offset(8)
            make.width.equalTo(210)
            make.height.equalTo(44)
        }
    }
    
    lazy var avatorImageView: UIImageView = {
        let imageV = UIImageView()
        imageV.layer.cornerRadius = 40
        imageV.layer.masksToBounds = true
        return imageV
    }()
    
    /// 性别图标
    lazy var sexImageView: UIImageView = {
        let imgView = UIImageView()
        imgView.contentMode = .scaleAspectFill
        return imgView
    }()
    
    lazy var nameLabel: UILabel = {
        let l = UILabel()
        l.font = PingFangSCSemiboldFont(18)
        l.textColor = UIColor.theme.main
        l.text = "- -"
        return l
    }()
    
    lazy var ageLabel: UILabel = {
        let l = UILabel()
        l.font = PingFangSCMediumFont(12)
        l.textColor = UIColor(hex: 0xebebeb)
        l.text = "- | -"
        return l
    }()
    
    lazy var invitationMessageView: GrowingTextView = {
        let textView = GrowingTextView()
        textView.frame = CGRect(x: 54, y: 190, width: 300, height: 100)
        textView.layer.cornerRadius = 3.0
        textView.placeholder = ""
        textView.font = PingFangSCRegularFont(16)
        textView.maxLength = 16
        //textView.delegate = self
        textView.minHeight = 100
        textView.maxHeight = 100
        return textView
    }()
    
    lazy var cofrimBtn: UIButton = {
        let btn = UIButton(type: .custom)
        btn.setTitle("同意加好友", for: .normal)
        btn.backgroundColor = UIColor.theme.main
        btn.addTarget(self, action: #selector(confrim), for: .touchUpInside)
        btn.setTitleColor(UIColor.text.x161616, for: .normal)
        btn.titleLabel?.font = PingFangSCSemiboldFont(16)
        btn.layer.cornerRadius = 22
        btn.layer.masksToBounds = true
        return btn
    }()
    
    lazy var rejectBtn: UIButton = {
        let btn = UIButton(type: .custom)
        btn.setTitle("拒绝", for: .normal)
        btn.addTarget(self, action: #selector(reject), for: .touchUpInside)
        btn.setTitleColor(UIColor.redpack.x5d5d5d, for: .normal)
        btn.titleLabel?.font = PingFangSCSemiboldFont(16)
        return btn
    }()
    
    
    //MARK: - click func
    @objc func confrim() {
        guard let info = info else { return }
        JMSGFriendManager.acceptInvitation(withUsername: info.username, appKey: info.appkey) { (result, error) in
            if error == nil {
                info.state = JCVerificationType.accept.rawValue
                JCVerificationInfoDB.shareInstance.updateData(info)
                //self.bindData(self.info)
                NotificationCenter.default.post(name: Notification.Name(rawValue: kUpdateFriendList), object: nil)
                //self.delegate?.acceptInvitation(userName: self.info.username, eventType: self.info.type, pushId: nil)
                self.delegate?.confrimInvitation(userName: info.username)
                DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1) {
                    self.navigationController?.popViewController(animated: true)
                }
            }
        }
    }
    
    @objc func reject() {
        guard let info = info else { return }
        JMSGFriendManager.rejectInvitation(withUsername: info.username, appKey: info.appkey, reason: "拒绝了你的好友请求") { (result, error) in
            if error == nil {
                info.state = JCVerificationType.reject.rawValue
                JCVerificationInfoDB.shareInstance.updateData(info)
                //self.bindData(self.info)
                NotificationCenter.default.post(name: Notification.Name(rawValue: kUpdateFriendList), object: nil)
                self.delegate?.rejectInvitation()
                DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1) {
                    self.navigationController?.popViewController(animated: true)
                }
            }
        }
    }
}


extension MTVerficateDetailViewController {

    override func yp_navigationBarTintColor() -> UIColor! {
        return UIColor(hex: 0xFFFFFF)
    }

    override func yp_navigtionBarConfiguration() -> YPNavigationBarConfigurations {
        return [.backgroundStyleColor, .styleBlack, .backgroundStyleOpaque]
    }

    override func yp_navigationBackgroundColor() -> UIColor! {
        return UIColor(hex: 0x000000)
    }
}
